<template>
  <!--  <PannelHeader :route="route"/>-->
  <pannel-header :route="route"></pannel-header>
  <div class="btns">
    <el-button @click="open" type="primary" :icon="Plus">新增</el-button>
  </div>
  <el-table :data="listData.list" style="width: 100%">
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="name" label="昵称"/>
    <el-table-column prop="permissionName" label="菜单权限" width="500px"/>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="open(scope.row)">
          编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-info">
    <el-pagination
        v-model:current-page="paginationData.pageNum"
        v-model:page-size="paginationData.pageSize"
        size="small"
        :page-sizes="[10, 20, 50, 100]"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-model="dialogFormVisible"
             title="添加权限"
             width="500"
             :before-close="beforeClose">
    <el-form :model="form"
             ref="formRef"
             label-position="left"
             :rules="rules">
      <!--这个item是隐藏域-->
      <el-form-item prop="id" v-show="false">
        <el-input v-model="form.id"/>
      </el-form-item>
      <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="权限" prop="permissions" :label-width="formLabelWidth">
        <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="treeData"
            show-checkbox
            node-key="id"
            highlight-current
            :props="defaultProps"
            :default-checked-keys="defaultCheckedkeys"
            :default-expanded-keys="[2]"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {reactive, ref, onMounted, nextTick} from 'vue'
import {menuList, userGetmenu, userSetmenu} from '../../../api'
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {useRoute} from 'vue-router'
import PannelHeader from "../../../components/pannel.vue";

const route = useRoute()
//树形节点
const treeRef = ref()
const defaultProps = reactive({
  children: 'children',
  label: 'label',
})
//树形数据
const treeData = reactive([])

//列表数据
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10
})
const listData = reactive({
  list: [],
  total: 0
})

onMounted(() => {
  userGetmenu().then(({data}) => {
    Object.assign(treeData, data.data)
  })
  getListData()
})

const getListData = () => {
  menuList(paginationData).then(({data}) => {
    console.log(data, 'data')
    listData.list = data.data.list
    listData.total = data.data.total
    console.log(listData, 'listData')
  })
}

//默认选中权限管理定义
const defaultCheckedkeys = [4, 5]

const dialogFormVisible = ref(false)
const formRef = ref()
const formLabelWidth = '80px'
const form = reactive({
  id: null,
  name: '',
  permissions: ''
})

//弹窗关闭
const beforeClose = () => {
  dialogFormVisible.value = false
  //重置表单
  formRef.value.resetFields()
  //树形区重置
  treeRef.value.setCheckedKeys(defaultCheckedkeys)
}

//打开新增的弹窗
const open = async (rowData = {}) => {
  dialogFormVisible.value = true
  //打开弹窗是异步的
  //编辑的情况下
  // 弹窗打开form是异步的
  await nextTick(() => {
    if (rowData) {
      Object.assign(form, {id: rowData.id, name: rowData.name, permissions: rowData.permissions})
      treeRef.value.setCheckedKeys(rowData.permission)
    }
  })
}

// 名称校验
const validateName = (rule, value, callback) => {
  // 不能为空
  if (!value || value === '') {
    callback(new Error('请输入名称'))
  } else {
    callback()
  }
}

// 表单校验
const rules = reactive({
  name: [{validator: validateName, trigger: 'blur'}],
})

//提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //获取选中的数上选中的节点
      form.permissions = JSON.stringify(treeRef.value.getCheckedKeys(false))
      console.log(form, 'submitForm')
      userSetmenu(form).then(({data}) => {
        console.log(data, 'userSetmenu-data')
        if (data.code === 10000) {
          ElMessage.success(data.message)
          dialogFormVisible.value = false
          beforeClose()
          getListData()
        } else {
          console.log(data, 'userSetmenu-data333')
          ElMessage.error(data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//page-size 改变时触发
const handleSizeChange = (val) => {
  paginationData.pageSize = val
  getListData()
}
//current-page 改变时触发
const handleCurrentChange = (val) => {
  paginationData.pageNum = val
  getListData()
}
</script>
<style lang="less" scoped>
.btns {
  padding: 10px 0px 10px 10px;
  background-color: #f6f4f4;
}

.pagination-info {
  padding: 10px 0;
  background-color: #fff;

  .el-pagination {
    justify-content: end;
  }
}
</style>
